<!DOCTYPE html>
<html>

<head>
  <title>WebSocket 测试</title>
</head>

<body>
  <h2>WebSocket 客户端</h2>
  <input type="text" id="clientId" placeholder="输入你的ID（如：user1）" value="user1" />
  <button onclick="connect()">连接</button>
  <button onclick="disconnect()">断开</button>
  <br><br>

  <input type="text" id="msg" placeholder="输入消息" />
  <select id="msgType">
    <option value="broadcast">广播</option>
    <option value="private">私聊</option>
  </select>
  <input type="text" id="toId" placeholder="目标ID（私聊时）" />
  <button onclick="send()">发送</button>

  <br><br>
  <div id="output" style="border:1px solid #ccc; height:300px; overflow-y:scroll;"></div>

  <script>
    let socket = null;

    function log(msg) {
      const output = document.getElementById('output');
      output.innerHTML += `<p>${new Date().toLocaleTimeString()}: ${msg}</p>`;
      output.scrollTop = output.scrollHeight;
    }

    function connect() {
      const clientId = document.getElementById('clientId').value;
      socket = new WebSocket(`ws://192.168.2.2:46835/ws?id=${clientId}`);

      socket.onopen = () => log('连接成功');
      socket.onmessage = (event) => log('收到: ' + event.data);
      socket.onclose = () => log('连接已关闭');
      socket.onerror = (error) => log('错误: ' + error);
    }

    function disconnect() {
      if (socket) socket.close();
    }

    function send() {
      const content = document.getElementById('msg').value;
      const type = document.getElementById('msgType').value;
      const to = document.getElementById('toId').value;

      const msg = { type, content };
      if (type === 'private') msg.to = to;

      socket.send(JSON.stringify(msg));
      document.getElementById('msg').value = '';
    }
  </script>
</body>

</html>